package com.hnucm.eatwhat_java;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.hnucm.eatwhat_java.act.AddActivity;
import com.hnucm.eatwhat_java.act.PriceActivity;
import com.hnucm.eatwhat_java.adapter.ShopAdapter;
import com.hnucm.eatwhat_java.dao.ShopDao;
import com.hnucm.eatwhat_java.dao.ShopDaoDataBase;
import com.hnucm.eatwhat_java.databinding.ActivityMainBinding;
import com.hnucm.eatwhat_java.pojo.Shop;
import com.hnucm.eatwhat_java.util.UtilApplication;
import com.hnucm.eatwhat_java.util.MyItemDecoration;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private String TAG="MainActivity";
    private ActivityMainBinding binding;
    private SwipeRecyclerView recyclerView;
    private ShopAdapter adapter;
    private ShopDao shopDao;
    private List<Shop> shopList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= DataBindingUtil.setContentView(this,R.layout.activity_main);

        EventBus.getDefault().register(this);

        //获取全局数据引用
        shopList=UtilApplication.getShopList();

        //1.和数据库建立连接(通过单例类封装)
        //2.返回的不是一个接口对象，返回的是一个接口的实现类  是运行期间动态生成的
        shopDao=UtilApplication.getShopDao();

        //3.操作数据库
        //增加数据
        shopList.clear();
        shopList.addAll(shopDao.getAllShop());

        //查询数据
        findViewById(R.id.button3).setOnClickListener(
            (view)->{
                shopList.clear();
                shopList.addAll(shopDao.getAllShop());
                adapter.notifyDataSetChanged();
            }
        );

        //绑定adapter
        recyclerView=binding.shopRecyclerview;
        adapter=new ShopAdapter(shopList,this);
//        bravhAdapter=new BravhShopAdapter(R.layout.shop_item,shopList);

        recyclerView.setSwipeMenuCreator((leftMenu, rightMenu, position) -> {
            int width = 200;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem deleteItem = new SwipeMenuItem(MainActivity.this)
                    .setBackgroundColor(Color.alpha(R.color.main_blue))
                    .setText("删除")
                    .setTextSize(20)
                    .setTextColor(Color.RED)
                    .setWidth(width)
                    .setHeight(height);
            rightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。.
        });
        recyclerView.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
            menuBridge.closeMenu();
            // 左侧还是右侧菜单：
            int direction = menuBridge.getDirection();
            // 菜单在Item中的Position：
            int menuPosition = menuBridge.getPosition();
            if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
                switch (menuPosition) {
                }
            } else if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                switch (menuPosition) {
                    case 0: {
                        Toast.makeText(MainActivity.this, "删除", Toast.LENGTH_SHORT).show();
                        List removeList=null;
                        removeList=shopDao.findAllShopById(((Shop) shopList.get(adapterPosition)).getId());
                        for (Object shop:removeList) {
                            shopDao.deleteShop((Shop) shop);
                        }
                        shopList.clear();
                        shopList.addAll(shopDao.getAllShop());
                        adapter.notifyDataSetChanged();
                    }
                    break;
                    default:
                        Toast.makeText(MainActivity.this, "默认", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        recyclerView.setAdapter(adapter);
        recyclerView.setLongPressDragEnabled(true);
        recyclerView.setOnItemMoveListener(onItemMoveListener);



                recyclerView.addItemDecoration(new MyItemDecoration(8));
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        //随机选择食物
        binding.goEatBtn.setOnClickListener(view -> {
            if(shopList.size()!=0){
                Random random=new Random();
                Log.d(TAG, "onCreate: "+shopList.size());
                int index=random.nextInt(shopList.size());
                Log.d(TAG, "onCreate: "+index);
                if(index>=0){
                    Shop shop1 =shopList.get(index);
                    binding.shopNameTxt.setText(shop1.getShopName());
                }
            }
        });

        //增加食物
        binding.fab.setOnClickListener(v -> {
            Intent intent=new Intent(MainActivity.this, AddActivity.class);
            startActivity(intent);
        });

        //抽奖
        binding.button2.setOnClickListener(v -> {
            Intent intent=new Intent(MainActivity.this, PriceActivity.class);
            startActivity(intent);
        });

        //清空数据库
        binding.clearBtn.setOnClickListener(v -> {

            AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("确认删清空所有数据吗?")
                .setPositiveButton("确认", (dialog, which) -> {
                    shopDao.deleteAllSHop(shopList);
                    shopList.clear();
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();

        });

        ImmersionBar.with(this).statusBarDarkFont(true).init();

    }

    //刷新数据
    /*定义一个public void的方法接收其他的Activity通过eventbus发出的消息*/
    @Subscribe(threadMode = ThreadMode.MAIN)/*并且设置接收方法的线程，这里在主线程，可以通过这个方法实现线程切换*/
    public void message(Shop shop){
        Shop shopTemp= shop;
        Log.d(TAG, "eventbus message: 刷新数据");
        if(shopTemp!=null){
            shopDao.insertShop(shopTemp);
            shopList.clear();
            shopList.addAll(shopDao.getAllShop());
            adapter.notifyDataSetChanged();

        }else{
            Toast.makeText(MainActivity.this,"shopTemp为空",Toast.LENGTH_SHORT).show();
        }
    }

    private OnItemMoveListener onItemMoveListener=new OnItemMoveListener() {
        @Override
        public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
            int srcPosition = srcHolder.getAbsoluteAdapterPosition();
            int targetPosition = targetHolder.getAbsoluteAdapterPosition();
            Collections.swap(shopList,srcPosition,targetPosition);
            adapter.notifyItemMoved(srcPosition,targetPosition);
            Log.e(TAG, "onItemMove: "+srcHolder.getAbsoluteAdapterPosition());
            return true;
        }

        @Override
        public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {

        }
    };
}